package cn.stronglink.assetmanage.business.inspection.model;

import android.os.Handler;
import android.support.v7.widget.CardView;
import android.widget.ExpandableListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.PatrolDao;
import cn.stronglink.assetmanage.entity.Patrol;
import cn.stronglink.assetmanage.entity.PatrolDetail;
import cn.stronglink.assetmanage.entity.RepailDetail;
import cn.stronglink.assetmanage.entity.Repair;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.entity.SearchAsset;
import cn.stronglink.assetmanage.entity.Task;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.netrequest.business.patrol.PatrolService;
import cn.stronglink.netrequest.business.search.SearchService;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by zhengjinglan on 2018/6/20.
 */

public class PatrolModel {
    private Gson gson = new Gson();
    private onPatrolDataListener onPatrolDataListener;
    private onSearchAssetListener onSearchAssetListener;
    private PatrolService patrolService;
    private SearchService searchService;
    private Handler mHandler;

    public PatrolModel(){
        searchService = new SearchService();
        patrolService = new PatrolService();
    }
    public PatrolModel.onSearchAssetListener getOnSearchAssetListener(){
        return onSearchAssetListener;
    }
    public void  setOnSearchAssetListener(PatrolModel.onSearchAssetListener onSearchAssetListener){
        this.onSearchAssetListener = onSearchAssetListener;
    }

    public PatrolModel.onPatrolDataListener getOnPatrolDataListener(){
        return onPatrolDataListener;
    }

    public void  setOnRepairDataListener(PatrolModel.onPatrolDataListener onPatrolDataListener){
        this.onPatrolDataListener = onPatrolDataListener;
    }

    /**
     * 从服务器获取巡检单
     */
    public void getRepairData(){
        try {

            patrolService.downloadPatrolWorkOrder(User.getInstance().getId_(), new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    if (onPatrolDataListener != null){
                        onPatrolDataListener.onFailure(call, e);
                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (onPatrolDataListener != null){
                        onPatrolDataListener.onResponse(call, response);
                    }
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public boolean savePatrolData(String resultJson){
        //id为单号 patrol_id是主键
        List<Patrol> patrolList = DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getPatrolDao().queryBuilder().distinct()
                .orderAsc(PatrolDao.Properties.Id).list();

        Map<String, Patrol> patrolMap = new HashMap<>();    //巡检到的商品
        for (int i=0; i<patrolList.size();i++){
            Patrol detail = patrolList.get(i);
            patrolMap.put(patrolList.get(i).getId_(),detail);
        }

        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).clear();
        Result<List<Patrol>> repairResult = null;
        repairResult = gson.fromJson(resultJson, new  TypeToken<Result<List<Patrol>>>(){
        }.getType());
        if(repairResult!=null&&repairResult.getHttpCode()== HttpURLConnection.HTTP_OK){
            if(repairResult.getData()!=null) {
                //遍历下载的的patrol和数据库中的patrol， 如果数据库中有就将数据库中的patrol给下载的patrol列表
                List<Patrol> inventoryList = repairResult.getData();

                // 巡检单列表
                if(inventoryList!=null&&inventoryList.size()>0){
                    for(Patrol patrol:inventoryList){
                        String  id_ = patrol.getId_();
                        if (!patrolMap.containsKey(id_)){
                            DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getPatrolDao().insert(patrol);
                            // 获取详情
                            if(patrol.getDetailList()!=null&&patrol.getDetailList().size()>0){
                                for (PatrolDetail detail:patrol.getDetailList()){
                                    detail.setOrderNo(patrol.getId_());
                                    DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getPatrolDetailDao().insert(detail);
                                }
                            }
                        }


                    }
                }

            }
            return true;
        }
        return false;
    }

    public void saveSearchAssetData(String resultJson){
        Result<List<SearchAsset>> repairResult = null;
        repairResult = gson.fromJson(resultJson, new  TypeToken<Result<List<SearchAsset>>>(){
        }.getType());
        if(repairResult!=null&&repairResult.getHttpCode()== HttpURLConnection.HTTP_OK){
            if(repairResult.getData()!=null) {
                List<SearchAsset> inventoryList = repairResult.getData();
                // 验收单列表
                if(inventoryList!=null&&inventoryList.size()>0){
                    deleteAllAssete();
                    for(SearchAsset patrol:inventoryList){
                        deleteAllAssete();
                        //将SearchAsset保存在任务表中
                        Task task = new Task();
                        task.setId(patrol.getId());
                        task.setId_(patrol.getId_());
                        task.setStatus(patrol.getStatus());
                        task.setBusinessType(Constants.STATUS_THREE);
                        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getTaskDao().insertOrReplace(task);
                        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getSearchAssetDao().insert(patrol);
                    }
                }

            }
        }
    }

    public void deleteAllRepair(){
        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getPatrolDao().deleteAll();
        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getPatrolDetailDao().deleteAll();
    }

    public void deleteAllAssete(){
        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getSearchAssetDao().deleteAll();
    }
    public interface onPatrolDataListener {
        void onFailure(Call call, IOException ex);

        void onResponse(Call call, Response response);
    }

    public interface onSearchAssetListener{
        void onAssetFailur(Call call, IOException ex);
        void onAssetResponse(Call call, Response response);
    }
}
